/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2019-11-13 18:41
 */
package com.yao.common.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yao.common.annotation.User;
import com.yao.common.config.converters.CustomMessageConverter;
import com.yao.common.config.interceptor.LoginInterceptor;
import com.yao.common.constant.SysConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yaoyuming
 * @date 2019/11/13 18:41
 */
@Configuration
@Slf4j
public class WebMvcConfigurerImpl implements WebMvcConfigurer {

    @Value("${auth.enable:false}")
    private boolean auth_enable;


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(argResolver());
//        resolvers.add(pageResolver());
    }

    /**
     * 功能描述 : 配置报文解析
     * @param converters
     * @author yaoyuming
     * @date 2020/4/16
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(CustomMessageConverter.fastJsonHttpMessageConverter());
//        converters.add(CustomMessageConverter.stringHttpMessageConverter());

    }


//    @Override
//    public void addViewControllers(ViewControllerRegistry registry) {
//        log.info("-------------------------------------addViewControllers-------------------------------------");
//        registry.addRedirectViewController("/login.html", "login.html");
//        registry.addViewController("/login").setViewName("login");
//    }

    /**
      * 功能描述 : 配置拦截器
      * @param registry
      * @author yaoyuming
      * @date 2020/5/19 0019
      */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        if(!auth_enable){
            return ;
        }

        // 拦截所有接口，除了登陆接口
        List<String> includes = Arrays.asList("/**");
        List<String> excludes = Arrays.asList("/home/index", "/home/login","/error", "/**/*.js", "/**/*.css", "/**/*.png ", "/**/*.woff", "/**/*.html", "/user/login")
                .stream().map(StrUtil::trim)
                .collect(Collectors.toList());

        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns(includes)
                .excludePathPatterns(excludes);

    }

    private HandlerMethodArgumentResolver argResolver() {
        return new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter methodParameter) {
                return methodParameter.hasParameterAnnotation(User.class);
            }

            @Override
            public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
                String current_user_id = nativeWebRequest.getHeader(SysConst.HEADER_USER_ID);
                return StrUtil.isBlank(current_user_id) ? 0 : Convert.toInt(current_user_id);
            }
        };
    }

    private HandlerMethodArgumentResolver pageResolver(){
        return new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter parameter) {
                return IPage.class.equals(parameter.getParameterType());
            }

            @Override
            public IPage resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
                //TODO 解析前端传输对象，构造IPage

                Map<String, String[]> parameterMap = webRequest.getParameterMap();

                parameterMap.forEach((k,v) -> System.out.println(k +" :: "+v));

                Iterator<String> parameterNames = webRequest.getParameterNames();
                while (parameterNames.hasNext()){
                    System.out.println("parameterNames.next() = " + parameterNames.next());
                }


                System.out.println("webRequest.getRemoteUser() = " + webRequest.getRemoteUser());

                return new Page(2, 10);
            }
        };
    }



}